package com.attendance.sz.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.Stack;

public class ClsPublic {

	private static boolean bIsop = false;// 没有点击则为false,否则为true
	private static int startCunt = 0;
	private static int iHFcmd = 0;// 指的HF模块的哪个命令字指行
	public static Session dl_Server = new Session(); // 与平台通信的队列
	public static Session dl_hfmode = new Session(); // 与模块通信的队列
	public static int imyDeivceID = -1;// 0--表示我的手机ANDROID设备
	public static int[] bwList1 = null;// 下标0存标志(0-挂失，1-解挂),下标1存黑名单个数,后面就是数据啦
	public static int[] bwList2 = null;// 下标0存标志(0-挂失，1-解挂),下标1存黑名单个数,后面就是数据啦
	public static int iTransListFlag = 0;// 0--名单初娩,1--正在处理中,2--已处理
	public static int iCardType = 0;// 0x01-M1卡2.0结构，0x02-M1卡1.2结构，0x10-CPU卡1.0结构
	public static long ltimeCounter = 0;//计数器
	public static String strppath;//相片路径
	public static String[] mStrings;
	public static long lFileNum;//文件总数
	public static long lPlayInterval;//;播放的时间间隔
	public static long lPlayImageStop;//;图片播时停留时间

	static {
		bwList1 = new int[257];// 下标0存标志(0-挂失，1-解挂),下标1存黑名单个数,后面就是数据啦
		bwList2 = new int[257];// 下标0存标志(0-挂失，1-解挂),下标1存黑名单个数,后面就是数据啦
		iTransListFlag = 0;// 0--名单初娩化,1--正在处理中,2--已处理
	}

	public static boolean getbIsop() {
		return bIsop;
	}

	public static void setbIsop(boolean a) {
		ClsPublic.bIsop = a;
	}

	public static int getstartCunt() {
		return startCunt;
	}

	public static void setstartCunt(int a) {
		ClsPublic.startCunt = a;
	}

	public static int getiHFcmd() {
		return iHFcmd;
	}

	public static void setiHFcmd(int a) {
		ClsPublic.iHFcmd = a;
	}

	// 整数到字节数组转换
	public static byte[] int2bytesBy32(int n) {
		byte[] ab = new byte[4];
		ab[0] = (byte) (0xff & n);
		ab[1] = (byte) ((0xff00 & n) >> 8);
		ab[2] = (byte) ((0xff0000 & n) >> 16);
		ab[3] = (byte) ((0xff000000 & n) >> 24);
		return ab;
	}

	// 整数到字节数组转换
	public static byte[] int2bytesBy16(int n) {
		byte[] ab = new byte[2];
		// ab[0] = (byte) (0xff & n);
		// ab[1] = (byte) ((0xff00 & n) >> 8);

		ab[0] = (byte) ((0xff00 & n) >> 8);
		ab[1] = (byte) (0xff & n);

		return ab;
	}

	// 字节数组到整数的转换
	public static int bytes2int(byte b[]) {
		int s = 0;
		s = ((((b[0] & 0xff) << 8 | (b[1] & 0xff)) << 8) | (b[2] & 0xff)) << 8
				| (b[3] & 0xff);
		return s;
	}

	// 字节转换到字符
	public static char byte2char(byte b) {
		return (char) b;
	}

	private final static byte[] hex = "0123456789ABCDEF".getBytes();

	private static int parse(char c) {
		if (c >= 'a')
			return (c - 'a' + 10) & 0x0f;
		if (c >= 'A')
			return (c - 'A' + 10) & 0x0f;
		return (c - '0') & 0x0f;
	}

	// 从字节数组到十六进制字符串转换
	public static String Bytes2HexString(byte[] b) {
		byte[] buff = new byte[2 * b.length];
		for (int i = 0; i < b.length; i++) {
			buff[2 * i] = hex[(b[i] >> 4) & 0x0f];
			buff[2 * i + 1] = hex[b[i] & 0x0f];
		}
		return new String(buff);
	}

	// 从字节数组到十六进制字符串转换 用这个
	public static String MyBytes2HexString(byte[] b) {
		String ret = "";
		for (int i = 0; i < b.length; i++) {
			String hex = Integer.toHexString(b[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			ret += hex.toUpperCase(Locale.getDefault());
			// ret += hex;
		}
		return ret;
	}

	// 从十六进制字符串到字节数组转换
	public static byte[] HexString2Bytes(String hexstr) {
		byte[] b = new byte[hexstr.length() / 2];
		int j = 0;
		for (int i = 0; i < b.length; i++) {
			char c0 = hexstr.charAt(j++);
			char c1 = hexstr.charAt(j++);
			b[i] = (byte) ((parse(c0) << 4) | parse(c1));
		}
		return b;
	}

	// 从十进制字符串到字节数组转换
	public static byte[] DexString2Bytes(String decstr) {
		String stTemp;
		byte[] b = new byte[decstr.length() / 2];
		int j = 0;

		for (int i = 0; i < decstr.length(); i += 2) {
			stTemp = decstr.substring(i, i + 2);
			b[j++] = (byte) Integer.parseInt(stTemp);
		}
		return b;
	}

	/**
	 * 字符串反转,前提每两个字符转如:2669CCDD==>DDCC6926,1234-->3412
	 * 
	 * @param orig
	 * @return
	 */
	public static String StrReverseByte(String orig) {
		String strr = "";
		int iLen = orig.length();
		for (int i = 0; i < iLen; i += 2) {
			strr = orig.substring(i, i + 2) + strr;
		}
		return strr;
	}

	/***
	 * 将16进制字符串进行高低位变换后转成数字字符串,如:"01000000"-->"1","A000000"-->"10"
	 * 
	 * @param orig
	 * @return 如:2669CC7F(2144102694) 2669CC80(2160879910) 注意负数也会变成相应的正数
	 */
	public static String StrConDigitFromS(String orig) {
		// 卡流水号:01000000 2669CC7F(2144102694) 2669CC80(2160879910)
		String strt = orig;// "2669CC80";//01000000(1) A000000(10) A0000000(160)
							// 2669CCDD(3721160998)
		String strr = "";
		strr = ClsPublic.StrReverseByte(strt);
		byte bb[] = ClsPublic.HexString2Bytes(strr);
		long iValue = ClsPublic.bytetoshort(bb);
		iValue = ClsPublic.getUnsignedLong(iValue);
		if (iValue < 0) {
			iValue = 0 - iValue;
			iValue = 4294967295L - iValue;
			iValue = iValue + 1;
		}
		String s = String.valueOf(iValue);
		return s;
	}

	public  static  void  reeboot(Context context){
		Intent intent2 = new Intent(Intent.ACTION_REBOOT);
		intent2.putExtra("nowait", 1);
		intent2.putExtra("interval", 1);
		intent2.putExtra("window", 0);
		context.sendBroadcast(intent2);

	}
	/***
	 * 将16进制字符串进行高低位变换后转成数字,如:"01000000"-->1,"A000000"-->10
	 * 
	 * @param orig
	 * @return 如:2669CC7F(2144102694) 2669CC80(2160879910) 注意负数也会变成相应的正数
	 */
	public static int StrConDigitFromI(String orig) {
		// 卡流水号:01000000 2669CC7F(2144102694) 2669CC80(2160879910)
		String strt = orig;// "2669CC80";//01000000(1) A000000(10) A0000000(160)
							// 2669CCDD(3721160998)
		String strr = "";
		strr = ClsPublic.StrReverseByte(strt);
		byte bb[] = ClsPublic.HexString2Bytes(strr);
		long iValue = ClsPublic.bytetoshort(bb);
		iValue = ClsPublic.getUnsignedLong(iValue);
		if (iValue < 0) {
			iValue = 0 - iValue;
			iValue = 4294967295L - iValue;
			iValue = iValue + 1;
		}

		return (int) iValue;
	}

	
	/***
	 * 将十进制字符串,如:"20150823133400"-->"20150822113400"
	 *将时间减掉16小时,这里不解，为什么平板是这样的??? 
	 * 如:20150823133400-16小时=20150822113400
	 * @param orig
	 * @return 方法首先转成秒,然后减掉后面的long秒值取一个新值再转成字符串
	 */
	public static String StrConChangeBet(String orig, long ltime) {
		String time = "";
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd.HHmmss");
		Date date = null;
		try {
			date = df.parse(orig);
			long llt = date.getTime();
			llt = llt - (ltime * 3600 * 1000)+1000;
			date.setTime(llt);
			time = df.format(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return time;
	}
	
	
	/**
	 * 从底层取年月日时分秒 分别存在字符串数组中，按顺序 字符0--年,字符1--月,字符2--日, 字符3--时,字符4--分,字符5--秒   
	 * @param st
	 */
	public static void GetDateA(String []stra){
		byte[] aa = new byte[64];

		String res = new String(aa);//,"UTF-8");//取得值:10/17/15 18:46:48 Sat
		String strTemp;
		
		
		strTemp = res.substring(0, 2);//月
		stra[1] = strTemp;
		strTemp = res.substring(3, 5);//日
		stra[2] = strTemp;
		strTemp = "20" + res.substring(6, 8);//年
		stra[0] = strTemp;
		strTemp = res.substring(9, 11);//时
		stra[3] = strTemp;
		strTemp = res.substring(12, 14);//分
		stra[4] = strTemp;
		strTemp = res.substring(15, 17);//秒
		stra[5] = strTemp;
		strTemp = res.substring(18, 21);//星期
		if (strTemp.equals("Sun")){
			stra[6] = "1";	
		}
		else if (strTemp.equals("Mon")){
			stra[6] = "2";	
		}
		else if (strTemp.equals("Tue")){
			stra[6] = "3";	
		}
		else if (strTemp.equals("Wed")){
			stra[6] = "4";	
		}
		else if (strTemp.equals("Thu")){
			stra[6] = "5";	
		}
		else if (strTemp.equals("Fri")){
			stra[6] = "6";	
		}
		else if (strTemp.equals("Sat")){
			stra[6] = "7";	
		}
		return;
	}
	
	/***
	 * 将16进制字符串转成十进制字符串,如:"0F0801140930"-->"150801200948","0f0514120d2a"-->
	 * "150520181342"
	 * 
	 * @param orig
	 * @return 方法首先转成16进制数组,然后一个一个转成数字,最后合成数字字符串
	 */
	public static String StrConDigitFromHex(String orig, boolean bFlag) {

		String strt = orig;// "0F0801140930"
		int i = 0;
		int value = 0;
		String strr = "";
		byte bb[] = ClsPublic.HexString2Bytes(strt);
		for (i = 0; i < bb.length; i++) {
			if (i == 3) {
				if (bFlag) {
					strr += ".";
				}
			}
			value = (int) bb[i];
			if (value < 0) {
				value = 0 - value;
				value = 255 - value;
				value = value + 1;
			}
			if (value >= 10) {
				strr += "" + value;
			} else {
				strr += "0" + value;
			}
		}

		return strr;
	}

	/***
	 * 将两个十进制字符串转成数字,然后比较,返回前者比后者的大小,如oriS=5,oriC=3,那么返回2,返之为-2,如果两个相等则返回0
	 * 
	 * @param
	 * @return
	 */
	public static long StrCompareDigitFromDec(String oriS, String oriC) {
		long iOriS = Long.valueOf(oriS, 10);
		long iOriC = Long.valueOf(oriC, 10);

		long lRet = iOriS - iOriC;
		if ( lRet < 0 ){
			return (0-lRet);
		}

		return lRet;
	}

	/**
	 * 取得黑名单个数1及数据,将个数数值不是字符串存入bwList中
	 * 
	 * @param sOri
	 *            ,如:sOri:00002f
	 *            000100000002000000030000000400000005000000060000000700000008000000090000000
	 *            a0000000b0000000c0000000d0000000e0000000f0000001100000015000000160000001700000018000000190000001a0000001b0000001c0000001d0000001e0000001f000000200000002100000022000000230000002400000025000000260000002700000028000000290000002a0000002b0000002c0000002d0000002e0000002f00000031000000320000003300000092d00300
	 * @return
	 */
	public static int GetBWList1Value(String sOri, int bwList[]) {
		String strTemp = "";
		int iTemp = 0;
		int ik = 0;
		int i = 0;
		int iSkip = 0;
		int iTotal = 0;
		if (sOri.equals("") || sOri.startsWith("7620")) {
			return 0;
		}

		strTemp = sOri.substring(0, 4);// 表示(0-挂失，1-解挂)
		strTemp += "0000";// 凑成8字符(4byte)
		iTemp = ClsPublic.StrConDigitFromI(strTemp);// 将16进制字符串进行高低位变换后转成数字,如:"01000000"-->1,"A000000"-->10
		bwList[ik++] = iTemp;

		strTemp = sOri.substring(4, 8);// //表示(黑名单个数)
		strTemp += "0000";// 凑成8字符(4byte)
		iTemp = ClsPublic.StrConDigitFromI(strTemp);
		bwList[ik++] = iTemp;
		iTotal = iTemp;

		for (i = 0; i < iTotal; i++) {
			strTemp = sOri.substring(8 + iSkip, 16 + iSkip);
			iTemp = ClsPublic.StrConDigitFromI(strTemp);
			bwList[ik + i] = iTemp;
			iSkip += 8;
		}

		return 1;
	}

	/**
	 * 取得黑名单个数2及数据,将个数数值不是字符串存入bwList中
	 * 
	 * @param sOri
	 *            :sOri:010002003000000034000000762004009c000000
	 * @return
	 */
	public static int GetBWList2Value(String sOri, int bwList[]) {
		int iRet = GetBWList1Value(sOri, bwList);

		return iRet;
	}

	public static int COM_CRC_POLYNOMIAL = 0x8408;
	public static int COM_CRC_PRESET_VALUE = 0xFFFF;
	

	public static int CalculateCRC16(byte[] data) {
		int i, j, m;
		int crc = COM_CRC_PRESET_VALUE;
		int number_of_bytes = data[0] - 2; // in a LEGIC command the first
											// byte of a array/string holds
											// the number of following bytes
		for (i = 0; i <= number_of_bytes; i++) // loop over all the bytes which
		{
			m = getUnsignedByte(data[i]); // are used to build the crc
			crc = crc ^ m; // xor the crc with the next byte
			for (j = 0; j < 8; j++) // loop over each bit
			{
				if ((crc & 0x0001) == 1) // if the last bit of the crc is 1
				{
					crc = (crc >> 1) ^ COM_CRC_POLYNOMIAL;// then xor the crc
															// with the
				} // polynom and shift the crc
				else // else shift the crc
				{
					crc = (crc >> 1);
				}
			}
		}
		return crc;
	}

	public static String CalculateStringCRC16(String hexstr) {
		byte[] data = ClsPublic.HexString2Bytes(hexstr);
		int intValue = CalculateCRC16(data);
		return ClsPublic.Bytes2HexString(ClsPublic.int2bytesBy16(intValue))
				.toLowerCase();
	}

	public static int getUnsignedByte(byte data) { // 将data字节型数据转换为0~255 (0xFF
													// 即BYTE)。
		return data & 0x0FF;
	}

	public static int getUnsignedShort(short data) { // 将data字节型数据转换为0~65535
														// (0xFFFF 即 WORD)。
		return data & 0x0FFFF;
	}

	public static long getUnsignedInt(int data) { // 将int数据转换为0~4294967295
													// (0xFFFFFFFF即DWORD)。
		return data & 0x0FFFFFFFF;
	}

	public static long getUnsignedLong(long data) { // 将int数据转换为0~4294967295
		// (0xFFFFFFFF即DWORD)。
		return data & 0xFFFFFFFF;
	}

	public static int bytetoshort(byte b[]) {

		int mask = 0xff;
		int temp = 0;
		int n = 0;
		for (int i = 0; i < 4; i++) {
			n <<= 8;
			temp = b[i] & mask;
			n |= temp;
		}
		return n;
	}

	// 设置IP地址
	public static boolean setIpWithTfiStaticIp(Context context,
			String ipAddress, String netMask, String getWay) {
		WifiManager wifiManager = (WifiManager) context
				.getSystemService(Context.WIFI_SERVICE);
		WifiConfiguration wifiConfig = null;
		WifiInfo connectionInfo = wifiManager.getConnectionInfo(); // 得到连接的wifi网络

		List<WifiConfiguration> configuredNetworks = wifiManager
				.getConfiguredNetworks();

		for (WifiConfiguration conf : configuredNetworks) {
			if (conf.networkId == connectionInfo.getNetworkId()) {
				wifiConfig = conf;
				break;
			}
		}

		if (android.os.Build.VERSION.SDK_INT < 11) { // 如果是android2.x版本的话

			ContentResolver ctRes = context.getContentResolver();
			android.provider.Settings.System.putInt(ctRes,
					android.provider.Settings.System.WIFI_USE_STATIC_IP, 1);
			android.provider.Settings.System.putString(ctRes,
					android.provider.Settings.System.WIFI_STATIC_IP, ipAddress);
			android.provider.Settings.System.putString(ctRes,
					android.provider.Settings.System.WIFI_STATIC_NETMASK,
					netMask);
			android.provider.Settings.System.putString(ctRes,
					android.provider.Settings.System.WIFI_STATIC_GATEWAY,
					getWay);

			// android.provider.Settings.System.putString(ctRes,
			// android.provider.Settings.System.WIFI_STATIC_NETMASK,
			// "255.255.255.0");
			// android.provider.Settings.System.putString(ctRes,
			// android.provider.Settings.System.WIFI_STATIC_GATEWAY,
			// "192.168.0.1");
			// android.provider.Settings.System.putString(ctRes,
			// android.provider.Settings.System.WIFI_STATIC_DNS1,"192.168.0.1");
			// android.provider.Settings.System.putString(ctRes,
			// android.provider.Settings.System.WIFI_STATIC_DNS2,"61.134.1.9");

			return true;

		} else { // 如果是android3.x版本及以上的话

			try {
				setIpAssignment("STATIC", wifiConfig);
				setIpAddress(InetAddress.getByName(ipAddress), 24, wifiConfig);
				// setGateway(InetAddress.getByName("192.168.3.1"), wifiConfig);
				// setDNS(InetAddress.getByName("192.168.0.1"), wifiConfig);
				wifiManager.updateNetwork(wifiConfig); // apply the setting

				System.out.println("静态ip设置成功！");
				return true;
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("静态ip设置失败！");
				return false;
			}
		}
	}

	private static void setIpAssignment(String assign,
			WifiConfiguration wifiConf) throws SecurityException,
			IllegalArgumentException, NoSuchFieldException,
			IllegalAccessException {
		setEnumField(wifiConf, assign, "ipAssignment");
	}

	private static void setIpAddress(InetAddress addr, int prefixLength,
			WifiConfiguration wifiConf) throws SecurityException,
			IllegalArgumentException, NoSuchFieldException,
			IllegalAccessException, NoSuchMethodException,
			ClassNotFoundException, InstantiationException,
			InvocationTargetException {

		Object linkProperties = getField(wifiConf, "linkProperties");
		if (linkProperties == null)
			return;
		Class<?> laClass = Class.forName("android.net.LinkAddress");
		Constructor<?> laConstructor = laClass.getConstructor(new Class[] {
				InetAddress.class, int.class });
		Object linkAddress = laConstructor.newInstance(addr, prefixLength);

		ArrayList<Object> mLinkAddresses = (ArrayList<Object>) getDeclaredField(
				linkProperties, "mLinkAddresses");
		mLinkAddresses.clear();
		mLinkAddresses.add(linkAddress);
	}

	private static Object getField(Object obj, String name)
			throws SecurityException, NoSuchFieldException,
			IllegalArgumentException, IllegalAccessException {

		Field f = obj.getClass().getField(name);
		Object out = f.get(obj);
		return out;
	}

	private static Object getDeclaredField(Object obj, String name)
			throws SecurityException, NoSuchFieldException,
			IllegalArgumentException, IllegalAccessException {

		Field f = obj.getClass().getDeclaredField(name);
		f.setAccessible(true);
		Object out = f.get(obj);
		return out;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private static void setEnumField(Object obj, String value, String name)
			throws SecurityException, NoSuchFieldException,
			IllegalArgumentException, IllegalAccessException {

		Field f = obj.getClass().getField(name);
		f.set(obj, Enum.valueOf((Class<Enum>) f.getType(), value));
	}

	// private static void setGateway(InetAddress gateway,WifiConfiguration
	// wifiConf)
	// throws SecurityException,
	// IllegalArgumentException, NoSuchFieldException,
	// IllegalAccessException, ClassNotFoundException,
	// NoSuchMethodException, InstantiationException,
	// InvocationTargetException {
	// Object linkProperties = getField(wifiConf, "linkProperties");
	// if (linkProperties == null)
	// return;
	//
	// if (android.os.Build.VERSION.SDK_INT >= 14) { // android4.x版本
	// Class<?> routeInfoClass = Class.forName("android.net.RouteInfo");
	// Constructor<?> routeInfoConstructor = routeInfoClass
	// .getConstructor(new Class[] { InetAddress.class });
	// Object routeInfo = routeInfoConstructor.newInstance(gateway);
	//
	// ArrayList<Object> mRoutes = (ArrayList<Object>)getDeclaredField(
	// linkProperties, "mRoutes");
	// mRoutes.clear();
	// mRoutes.add(routeInfo);
	// } else { // android3.x版本
	// ArrayList<InetAddress> mGateways = (ArrayList<InetAddress>)
	// getDeclaredField(
	// linkProperties, "mGateways");
	// mGateways.clear();
	// mGateways.add(gateway);
	// }
	// }
	//
	// private static void setDNS(InetAddress dns, WifiConfiguration wifiConf)
	// throws SecurityException, IllegalArgumentException,
	// NoSuchFieldException, IllegalAccessException{
	// Object linkProperties = getField(wifiConf, "linkProperties");
	// if (linkProperties == null)
	// return;
	// ArrayList<InetAddress> mDnses = (ArrayList<InetAddress>)
	// getDeclaredField(linkProperties, "mDnses");
	// mDnses.clear(); // 清除原有DNS设置（如果只想增加，不想清除，词句可省略）
	// mDnses.add(dns);
	// //增加新的DNS
	// }

	public static String getLocalIpAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();

				if (intf.getName().toLowerCase().equals("eth0")
						|| intf.getName().toLowerCase().equals("wlan0")) {
					for (Enumeration<InetAddress> enumIpAddr = intf
							.getInetAddresses(); enumIpAddr.hasMoreElements();) {
						InetAddress inetAddress = enumIpAddr.nextElement();
						if (!inetAddress.isLoopbackAddress()) {
							String ipaddress = inetAddress.getHostAddress()
									.toString();
							if (!ipaddress.contains("::")) {// ipV6的地址
								return ipaddress;
							}
						}
					}
				} else {
					continue;
				}
			}
		} catch (SocketException ex) {

		}

		return null;
	}

	public static String getIp(Context context) {

		try {
			// 获取wifi服务
			WifiManager wifiManager = (WifiManager) context
					.getSystemService(Context.WIFI_SERVICE);
			// 判断wifi是否开启
			if (!wifiManager.isWifiEnabled()) {
				wifiManager.setWifiEnabled(true);
			}
			WifiInfo wifiInfo = wifiManager.getConnectionInfo();
			int ipAddress = wifiInfo.getIpAddress();
			String ip = intToIp(ipAddress);

			return ip;
		} catch (Exception ex) {

		}

		return null;
	}

	private static String intToIp(int i) {

		return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
				+ "." + (i >> 24 & 0xFF);
	}

	// for (Enumeration<NetworkInterface> en = NetworkInterface
	// .getNetworkInterfaces(); en.hasMoreElements();) {
	// NetworkInterface intf = en.nextElement();
	// if (intf.getName().toLowerCase().equals("eth0") ||
	// intf.getName().toLowerCase().equals("wlan0")) {
	// for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
	// enumIpAddr.hasMoreElements();) {
	// InetAddress inetAddress = enumIpAddr.nextElement();
	// if (!inetAddress.isLoopbackAddress()) {
	// ipaddress = inetAddress.getHostAddress().toString();
	// if(!ipaddress.contains("::")){//ipV6的地址
	// return ipaddress;
	// }
	// }
	// }
	// } else {
	// continue;
	// }
	// }

	public static int GetSocketCrc(byte[] data, int length) {
		int crc = 0;
		int i, j, m;

		for (j = 0; j < length; j++) {
			m = getUnsignedByte(data[j]);
			crc ^= m;
			for (i = 0; i < 8; i++) {
				if ((crc & 0x01) != 0) {
					crc >>= 1;
					crc ^= 0x8c;
				} else {
					crc >>= 1;
				}
			}
		}

		return crc;
	}

	// /*
	// 参数:
	// buf[]:参与校验的数组
	// Len：参与校验的数据长度
	// 返回值：校验值
	// */
	// unsigned char CalcCRC(unsigned char buf[], unsigned int Len)
	// {
	// unsigned char Crc = 0;
	// int i,j;
	//
	// for(j=0; j<Len; j++)
	// {
	// Crc ^= buf[j];
	// for(i=0; i<8; i++)
	// {
	// if ((Crc & 0x01) != 0)
	// {
	// Crc >>= 1;
	// Crc ^= 0x8c;
	// }
	// else
	// {
	// Crc >>= 1;
	// }
	// }
	// }
	// return Crc;
	// }

	public static void wq_UdpSendData(final String strIP, final String strPort, final String strData) {
		new Thread() {
			public void run() {
				try {
					// 1. 创建一个DatagramSocket对象
		
					DatagramSocket socket = new DatagramSocket(40000);
		
					// 2. 创建一个 InetAddress ， 相当于是地址
		
					// InetAddress serverAddress =
					// InetAddress.getByName("想要发送到的那个IP地址");
					InetAddress serverAddress = InetAddress.getByName(strIP);//strDestIP);// "192.168.0.71");
		
					// 3. 这是随意发送一个数据
		
					String str = "hello";
					str = strData;
		
					// 4. 转为byte类型
		
					byte data[] = str.getBytes();
		
					// 5. 创建一个DatagramPacket 对象，并指定要讲这个数据包发送到网络当中的哪个地址，以及端口号
					int iport = Integer.valueOf(strPort);
					DatagramPacket sendPacket = new DatagramPacket(data, data.length,
							serverAddress, iport);//iDestPort);// 8080);
		
					// 6. 调用DatagramSocket对象的send方法 发送数据
		
					socket.send(sendPacket);
		
					socket.close();
		
					return ;
				} catch (Exception e) {
					
					e.printStackTrace();
		
				}
		
				return ;
			}
		
		}.start();
	}
	
	public static void SetDateTime(final String strTime){
		new Thread() {
			public void run() {
				try {
					Process process = Runtime.getRuntime().exec("su");
					String datetime=strTime;//"20131023.112800"; //测试的设置的时间【时间格式 yyyyMMdd.HHmmss】
					DataOutputStream os = new DataOutputStream(process.getOutputStream());
					//DataInputStream is = new DataInputStream(process.getInputStream());
					InputStream fis = process.getInputStream();
					 BufferedReader br = new BufferedReader(new InputStreamReader(fis));
					 os.writeBytes("/system/bin/date\n");//先查一下时间
					//os.writeBytes("setprop persist.sys.timezone GMT+08:00\n");//设时间的时区:GMT+08:00,中国标准时间
					os.writeBytes("setprop persist.sys.timezone Asia/Shanghai\n");
					os.writeBytes("/system/bin/date -s "+datetime+"\n");//如:date -s 20151017.143300
					//os.writeBytes("clock -w\n");
					os.writeBytes("exit\n");
					os.flush();
					String line = null;
					logMa.d("martrin", "date -s "+datetime);
					while ((line = br.readLine()) != null) { 
						logMa.d("martrin", "r:"+line);
					} 
					logMa.d("martrin", "date cmd!\n");

				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}.start();
	}
	
	public static void httpdownFile(final String url) {

		new Thread() {
			public void run() {
				HttpClient client = new DefaultHttpClient();
				HttpGet get = new HttpGet(url);
				HttpResponse response;
				try {
					response = client.execute(get);
					HttpEntity entity = response.getEntity();
					long length = entity.getContentLength();
					InputStream is = entity.getContent();
					FileOutputStream fileOutputStream = null;
					if (is != null) {
						String filename = "";
						filename = ClsPublic.getName(url);
						File file = new File(
								//Environment.getExternalStorageDirectory()
								//		+ "/Attendance/" + "photo" + "/",
								ClsPublic.strppath,
								filename);

						fileOutputStream = new FileOutputStream(file);
						byte[] buf = new byte[1024 * 10];
						int ch = -1;
						int count = 0;
						while ((ch = is.read(buf)) != -1) {
							fileOutputStream.write(buf, 0, ch);

							count += ch;
							Log.i("update", "download " + count);
							if (length > 0) {

							}
						}
					}
					fileOutputStream.flush();

					if (fileOutputStream != null) {
						fileOutputStream.close();
					}
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}.start();

	}

	public static JSONObject get(String url) {
		StringBuffer strJson = new StringBuffer();
		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(url);
		HttpResponse response;
		try {
			response = client.execute(get);
			HttpEntity entity = response.getEntity();
			InputStream is = entity.getContent();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(is));

			String line;
			while ((line = reader.readLine()) != null) {
				strJson.append(line);
			}
		} catch (ClientProtocolException e) {
			return null;
		} catch (IllegalStateException e) {

			e.printStackTrace();
			return null;
		} catch (IOException e) {

			e.printStackTrace();
			return null;
		}

		if (strJson.length() <= 0) {
			logMa.d("martrin", "get empty json file...");
			return null;
		}

		logMa.d("martrin", "get json " + strJson.toString());

		JSONObject object = null;
		try {
			object = new JSONObject(strJson.toString());
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return object;
	}

	public static String GetFilePath(String filed, String fileName) {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			String strTemp = fileName.substring(fileName.length()-3, fileName.length());
			// filePath="/mnt/sdcard/Attendance/photo/"--内置;或:"/mnt/extsd/Attendance/photo/";---外置
			String filePath = Environment.getExternalStorageDirectory()
					+ "/Attendance/" + filed + "/";
			// 方法:1.先从外置SD上找(/mnt/extsd/Attendance/photo)，再从内置SD上找
			filePath = "/mnt/extsd/Attendance/" + filed + "/";
			if (  strTemp.equals("jpg") ){
				ClsPublic.strppath = filePath;//相片路径
			}
			//filePath = "/mnt/extsd/Attendance/" + filed + "/";
			File temp = new File(filePath);
			if (!temp.exists()) {
				temp.mkdirs();
			}

			filePath = filePath + fileName;
			File f = new File(filePath);

			// 可读
			if (f.canRead()) {
				return filePath;
			}

			//再从内置SD卡上找(/mnt/extsd/Attendance/photo/)
			//filePath = "/mnt/sdcard/Attendance/" + filed + "/";
//			filePath = "/mnt/sdcard/Attendance/" + filed + "/";
//			if (  strTemp.equals("jpg") ){
//				ClsPublic.strppath = filePath;//相片路径
//			}
//			File tempp = new File(filePath);
//			if (!tempp.exists()) {
//				tempp.mkdirs();
//			}
//
//			filePath = filePath + fileName;
//			File ff = new File(filePath);
//
//			// 可读
//			if (ff.canRead()) {
//				return filePath;
//			}
		}

		return null;
	}

	/***
	 * 根据全路径名获取文件名
	 * 
	 * @param strPathName
	 * @return
	 */
	public static String getName(String strPathName) {
		int iIndex = strPathName.lastIndexOf("/");
		if (iIndex == -1) {
			return strPathName;
		}
		String ss = strPathName.substring(iIndex + 1);

		return ss;
	}

	/***
	 * 根据全路径名获取路径
	 * 
	 * @param strPathName
	 * @return
	 */
	public static String getPath(String strPathName) {
		int iIndex = strPathName.lastIndexOf("/");
		if (iIndex == -1) {
			return strPathName;
		}
		String ss = strPathName.substring(0, iIndex + 1);

		return ss;
	}

	/**
	 * 字符串反转的七种方法
	 * 
	 * @param s
	 * @return
	 */
	public static String reverse1(String s) {
		int length = s.length();
		if (length <= 1)
			return s;
		String left = s.substring(0, length / 2);
		String right = s.substring(length / 2, length);
		return reverse1(right) + reverse1(left);
	}

	public static String reverse2(String s) {
		int length = s.length();
		String reverse = "";
		for (int i = 0; i < length; i++)
			reverse = s.charAt(i) + reverse;
		return reverse;
	}

	public static String reverse3(String s) {
		char[] array = s.toCharArray();
		String reverse = "";
		for (int i = array.length - 1; i >= 0; i--)
			reverse += array[i];
		return reverse;
	}

	public static String reverse4(String s) {
		return new StringBuffer(s).reverse().toString();
	}

	public static String reverse5(String orig) {
		char[] s = orig.toCharArray();
		int n = s.length - 1;
		int halfLength = n / 2;
		for (int i = 0; i <= halfLength; i++) {
			char temp = s[i];
			s[i] = s[n - i];
			s[n - i] = temp;
		}
		return new String(s);
	}

	public static String reverse6(String s) {
		char[] str = s.toCharArray();
		int begin = 0;
		int end = s.length() - 1;
		while (begin < end) {
			str[begin] = (char) (str[begin] ^ str[end]);
			str[end] = (char) (str[begin] ^ str[end]);
			str[begin] = (char) (str[end] ^ str[begin]);
			begin++;
			end--;
		}
		return new String(str);
	}

	public static String reverse7(String s) {
		char[] str = s.toCharArray();
		Stack<Character> stack = new Stack<Character>();
		for (int i = 0; i < str.length; i++)
			stack.push(str[i]);
		String reversed = "";
		for (int i = 0; i < str.length; i++)
			reversed += stack.pop();
		return reversed;
	}

	/**
	 * 字符串 java的Integer类提供了ParseInt静态方法接受String作为参数，可以将字符串转换为Integer：
	 */
	public int convertStringToInt(String s) {

		String sValue = s;// "5";
		int iValue = 0;

		try {
			iValue = Integer.parseInt(sValue);
		} catch (NumberFormatException ex) {
			System.out
					.println("The String does not contain a parsable integer");
			iValue = 0;
		}

		return iValue;

	}

	//public static void killAll(String strName) {
	//	ActivityManager mActivityManager = (ActivityManager)MyApplication.getApp().getAppContext().getSystemService(Context.ACTIVITY_SERVICE);
	//	List<ActivityManager.RunningAppProcessInfo> mRunningProcess = mActivityManager.getRunningAppProcesses();
	//	int i = 1;
	//	for (ActivityManager.RunningAppProcessInfo amProcess : mRunningProcess)
	//	{
	//		logMa.dt("martrin", (i++) + "PID: " + amProcess.pid + "(processName=" + amProcess.processName + "UID="+amProcess.uid+")");
	//		
	//	} 
	//	
	//}
	
	
}
